/*
 * numberFormatWithComma(s,type)
 * 功能：金额按千位逗号分割
 * 参数：s，需要格式化的金额数值. 传入数字number or init
 * 参数：type,判断格式化后的金额是否需要小数位. 取值： 0, 1
 * 返回：返回格式化后的数值字符串.
 */
export function numberFormatWithComma(s: number | string, type: number) {
  if (/[^0-9.]/.test(s as string)) return "0";
  if (s === null || s === "") return "0";
  if (s.toLocaleString().includes(",")) return s.toLocaleString();
  s = s.toString().replace(/^(\d*)$/, "$1.");
  s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
  s = s.replace(".", ",");
  const re = /(\d)(\d{3},)/;
  while (re.test(s)) s = s.replace(re, "$1,$2");
  s = s.replace(/,(\d\d)$/, ".$1");
  if (type === 0) {
    // 不带小数位(默认是有小数位)
    const a = s.split(".");
    if (a[1] === "00") {
      s = a[0];
    }
  }
  return s;
}

/**
 * 对大型数字进行四舍五入取整运算，例如 119000 => 12万
 * @param origin
 */
export function parseIntBigNum(origin: string | number) {
  const data = parseInt(String(origin), 10);
  let num = data;
  let unit = "";
  if (data >= 100000000) {
    num = Math.round(data / 100000000);
    unit = "亿";
  } else if (data >= 10000) {
    num = Math.round(data / 10000);
    unit = "万";
  }

  return {
    num,
    unit,
    full: num + unit,
  };
}

export function parseFloatBigNum(origin: string | number, fixed = 2) {
  const data = parseInt(String(origin), 10);
  let num = data;
  let unit = "";

  if (num >= 100000000000) {
    num = Number((num / 100000000000).toFixed(fixed));
    unit = "千亿";
  } else if (data >= 100000000) {
    num = Number((data / 100000000).toFixed(fixed));
    unit = "亿";
  } else if (data >= 10000) {
    num = Math.round(data / 10000);
    unit = "万";
  }

  return {
    num,
    unit,
    full: `${unit && "约"}${num + unit}`,
  };
}
